import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

// import './style.less';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, message, Modal, Tree } from 'antd';
import { debounce } from 'lodash';
import AddModal from './AddModal';
import AddModalSon from './AddModalson';

import Access from '@/components/Access';
import {
  sysOrgControllerList as getList,
  sysOrgControllerRemove as removeTee,
  sysOrgControllerTree as OragList,
} from '@/services/ess/sysOrg';
import 'react-perfect-scrollbar/dist/css/styles.css';
import { useAccess, useIntl } from 'umi';
import styles from '../index.less';

// const { Search } = Input;
interface treeProps {
  handleClick?: () => void;
  deleteCall?: () => void;
}

const TreeList = forwardRef(({ handleClick, deleteCall }: treeProps, ref: any) => {
  const [treeData, setTreeData] = useState<any>([]);
  const [TreeALL, setTreeALL] = useState<any>([]);
  const [selectNodeID, setselectNodeID] = useState<any>('');
  const [orgName, setorgName] = useState<any>(null);
  const { confirm } = Modal;
  const access = useAccess();
  const intl = useIntl();

  const queryTreeList = async (res: API.sysOrgControllerTreeParams) => {
    let result: any;
    result = await OragList(res);
    if (result) {
      setTreeData(result.data);
    }
  };

  const queryTeeAll = async () => {
    let result: any;
    result = await OragList({ orgName: '' });
    if (result) {
      setselectNodeID(result?.data[0]?.['id']);
      handleClick(result?.data[0]?.['id'], result.data);
      setTreeALL(result.data);
    }
  };

  useImperativeHandle(ref, () => ({
    queryTreeList: () => {
      queryTreeList({ orgName: '' });
    },
  }));

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setorgName(value);
  };

  const DeleteTree = async () => {
    const result = await getList({ orgId: selectNodeID });
    let length = result.data?.records?.length;
    if (length) {
      message.info(intl.formatMessage({ id: 'systemManagement.neddTochange.existingUsersInOrg' }));
    } else {
      confirm({
        title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
        content: intl.formatMessage({
          id: 'systemManagement.supplementary.dataCannotBeRestoredAfterDeletion',
        }),
        onOk() {
          removeTee({ orgId: selectNodeID }).then((res) => {
            if (res.success) {
              message.success(
                intl.formatMessage({
                  id: 'global.delSuccess',
                }),
              );
              queryTeeAll();
              queryTreeList({ orgName: orgName });
              deleteCall();
            }
          });
        },
        onCancel() {},
      });
    }
  };

  const TreeSelectMethod = (selectedKeys, target) => {
    if (selectedKeys.length === 0) {
      return;
    }
    handleClick(target.node.id, TreeALL);
    setselectNodeID(target.node.id);
  };

  const handleAddSubmit = (res: any) => {
    if (res) {
      queryTreeList({ orgName: orgName });
      queryTeeAll();
    }
  };

  const handleAddsonSubmit = (res: any) => {
    if (res) {
      queryTreeList({ orgName: orgName });
    }
  };

  useEffect(() => {
    queryTeeAll();
    queryTreeList({ orgName: orgName });
  }, []);

  useEffect(() => {
    queryTreeList({ orgName: orgName });
  }, [orgName]);

  return (
    <>
      <div className={styles.treeWrap} ref={ref}>
        <div className={styles.treeTop}>
          <Input
            style={{ width: '95%', margin: '12px 8px' }}
            placeholder={intl.formatMessage({
              id: 'systemManagement.organizationalManagementMenu.pleaseEnterTheOrganizationName',
            })}
            suffix={<SearchOutlined style={{ color: 'rgba(0,0,0,.45)' }} />}
            onChange={debounce(onChange, 300)}
            className="{styles.tree_search}"
          />
          <div className={styles.tree}>
            {selectNodeID && (
              <Tree
                blockNode
                defaultSelectedKeys={[selectNodeID]}
                fieldNames={{ title: 'name', key: 'id', children: 'children' }}
                treeData={treeData}
                onSelect={TreeSelectMethod}
                titleRender={(data: any) => {
                  data.value = (
                    <div style={{ lineHeight: '32px' }}>{data.isOperate ? '' : data.name}</div>
                  );
                  return <div>{data.value}</div>;
                }}
              />
            )}
          </div>
        </div>

        <div className={styles.treeBottom}>
          <AddModal handleAddSubmit={handleAddSubmit} />
          <AddModalSon
            handleAddsonSubmit={handleAddsonSubmit}
            parentId={selectNodeID}
            TreeALL={TreeALL}
          ></AddModalSon>
          <Access accessible={access['sys:org:del']} key="deleteOrg">
            <Button
              type="primary"
              size="middle"
              danger
              onClick={DeleteTree}
              disabled={selectNodeID === ''}
            >
              {intl.formatMessage({ id: 'systemManagement.organizationalManagementMenu.delete' })}
            </Button>
          </Access>
        </div>
      </div>
    </>
  );
});

export default TreeList;
